﻿/*
 * Copyright (C) 2011 The Calculator for Android Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.japminh.tool.calculator.util;

import net.japminh.tool.calculator.Const;
import net.japminh.tool.calculator.model.CalculateType;

/**
 * Doubleを処理するクラス
 * 
 * @author thangns
 *
 */
public final class DoubleUtils {

	private DoubleUtils() {

	}

	/**
	 * 演算を行う
	 * 
	 * @param value1
	 * @param value2
	 * @param type
	 * @return
	 */
	public static final double calculation(double value1, double value2, CalculateType type) {
		double result = 0.0;
		switch (type) {
		case Divide:
			result = value1 / value2;
			break;

		case Minus:
			result = value1 - value2;
			break;

		case Multiply:
			result = value1 * value2;
			break;

		case Plus:
			result = value1 + value2;
			break;
		}

		if (result > Const.MAX_VALUE) {
			result = Double.NaN;
		}
		return result;
	}

	/**
	 * @param value
	 * @return
	 */
	public static final String round(double value) {
		if (Double.isNaN(value) || (value > Const.MAX_VALUE)) {
			return null;
		}

		String result = String.format(Const.FORMAT_STRING, value);
		//result = result.substring(0, Math.min(result.length(), Const.INPUT_MAX_LENGTH));

		int indDot = result.indexOf('.');
		if (indDot >= 0) {
			int l1 = Math.max(0, Const.INPUT_MAX_LENGTH - (indDot + 1));
			result = String.format("%." + l1 + "f", value);

			int ind = result.length() - 1;
			while ((ind >= indDot) && ((result.charAt(ind) == '0') || result.charAt(ind) == '.')) {
				ind--;
			}
			result = result.substring(0, ind + 1);
		}

		return result;
	}
}
